<template>
    <div class='container'>
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="150px" class="demo-ruleForm">
        <div v-show="showForm">
            <div class="container" style="margin-top:20px">
                <h3 style="margin-bottom: 20px">{{title}}</h3>
				<el-row>
					<el-col>
						<el-form-item label="原料类型：" >
					    <!-- <el-radio-group  label="原料类型"> -->
					       {{ruleForm.type}}
					    <!-- </el-radio-group> -->
					</el-form-item>
					</el-col>

				</el-row>
                <el-row>
                    <el-col :span="12" v-if='switchHeadTab == "生产系统"'>
                        <el-form-item label="标准类型：" v-if="this.ruleForm.materialType !='中药材' && this.ruleForm.materialType != '辅料'">
                            {{standard}}
                        </el-form-item>
                    </el-col>
                  <el-col >
                    <el-form-item label="物料名称：">
                      {{ruleForm.breedName}}
                    </el-form-item>
                  </el-col>
                  <el-col v-if="ruleForm.type=='配方颗粒' && ruleForm.standard == '2'">
                    <el-form-item label="中药配方颗粒执行标准：">
                      {{ruleForm.checkName}}
                    </el-form-item>
                  </el-col>
                  <div v-else>
                    <el-col>
                      <el-form-item label="中药饮片颗粒执行标准：" v-if="ruleForm.type=='提取饮片'">
                        {{ruleForm.checkName}}
                      </el-form-item>
                      <el-form-item label="中药配方颗粒执行标准：" v-if="ruleForm.type=='配方颗粒'">
                        {{ruleForm.checkName}}
                      </el-form-item>
                      <el-form-item label="检验标准文件："  style="width:500px">
                        <img :src="imgurl" alt="" style="width:200px;height:200px;">
                      </el-form-item>
                    </el-col>
                    <el-col :span="12" >
                      <el-form-item label="检验标准描述：" >
                        {{ruleForm.description}}
                      </el-form-item>
                    </el-col>
                  </div>

                </el-row>
            </div>
            <el-form-item class="footerFixed">
                <el-button type="primary" @click="submitForm()">确认无误</el-button>
                <el-button @click="editback">返回修改</el-button>
            </el-form-item>
        </div>
        <div v-show = "show">
            <div class="container" style="margin-top:20px">
                <h3 style="margin-bottom: 20px">{{title}}</h3>
                <el-row>
                    <el-form-item label="原料类型：" prop="materialType">
                        <el-radio-group v-model="ruleForm.type">
                            <el-radio v-if='switchHeadTab == "生产系统"' label="中药材" border>中药材</el-radio>
                            <el-radio v-if='switchHeadTab == "生产系统"' label="辅料" border>辅料</el-radio>
                            <el-radio v-if='switchHeadTab == "生产系统"' label="提取饮片" border>提取饮片</el-radio>
                            <el-radio v-if='switchHeadTab == "生产系统"' label="配方颗粒(浸膏粉)" border>配方颗粒(浸膏粉)</el-radio>
                            <el-radio v-if='switchHeadTab == "生产系统"' label="配方颗粒" border>配方颗粒</el-radio>
                            <el-radio v-if='switchHeadTab == "生产系统"' label="配方颗粒(颗粒)" border>配方颗粒(颗粒)</el-radio>
                            <el-radio v-if='switchHeadTab == "中药饮片"' label="中药饮片" border>中药饮片</el-radio>
                            <el-radio v-if='switchHeadTab == "中药饮片"' label="中药饮片(半成品)" border>中药饮片(半成品)</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-row>
                <el-row>

                  <el-col >
                    <el-form-item label="物料名称：" >
                      {{ruleForm.breedName}}
                    </el-form-item>
                  </el-col>
                    <el-col :span="12" v-if='switchHeadTab == "生产系统"'>
                        <el-form-item label="标准类型：" prop="standard"  v-if="this.ruleForm.materialType !='中药材' && this.ruleForm.materialType != '辅料'">
                            <el-select v-model="ruleForm.standard"   filterable placeholder="请选择" style="width:auto;">
                                <el-option label="国标" value="1"></el-option>
                                <el-option label='省标' value="2"></el-option>
                                <el-option label='省标-北京' value="3"></el-option>
                                <el-option label='省标-上海' value="4"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                  <div>
                    <el-col>
                      <el-form-item :label="ruleForm.type+'执行标准'" prop="checkName" v-if="ruleForm.type=='配方颗粒'&&ruleForm.standard=='1'">
                        <el-input placeholder="请输入内容" v-model.trim="ruleForm.checkName" style="width:300px">
                        </el-input>
                      </el-form-item>
                      <el-form-item :label="ruleForm.type+'执行标准'" prop="checkName2" v-else>
                        <el-input placeholder="请输入内容" v-model.trim="ruleForm.checkName2" style="width:300px">
                        </el-input>
                      </el-form-item>
                      <el-form-item label="检验标准文件："  style="width:500px">
                        <upload-img ref="uploadChang" :maxNum="1" :files='listUrl'></upload-img>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12" >
                      <el-form-item label="检验标准描述：" >
                        <el-input placeholder="请输入内容"  v-model.trim="ruleForm.description" style="width:300px">
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </div>

                </el-row>
            </div>
            <el-form-item class="footerFixed">
                <el-button type="primary" @click="submitrule('ruleForm')">提交</el-button>
                <el-button @click="backPage">返回</el-button>
            </el-form-item>
        </div>
        <div class="container" v-show="ruleForm.type == '配方颗粒' && ruleForm.standard != 1" style="margin-top: 20px">
          <el-row>
            <el-button type="primary" style="float:right; margin-right: 10px"   @click="handleadded">添加标准</el-button>
          </el-row>
            <el-table
                    :data="tableData"
                    border
                    ref="multipleTable"
                    style="margin-top: 20px"
                    header-cell-class-name="table-header"
            >
                <el-table-column prop="address" sortable label="地址"></el-table-column>
                <el-table-column prop="checkName" sortable label="标准名称"></el-table-column>
                <el-table-column prop="fileName" sortable label="文件名"></el-table-column>
                <el-table-column prop="states" sortable label="状态">

                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                  <template slot-scope="scope">
                    <el-button
                        type="text"

                        @click="handleEdit(scope.$index, scope.row)"
                    >修改</el-button>
                    <el-button
                        type="text"
                        style="color: red"
                        @click="handledel(scope.$index, scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
            </el-table>
        </div>
          <el-dialog title="添加标准" customClass="customWidth" :visible.sync="dialogFormVisible" >
            <el-form :model="form" :label-position="labelPosition" label-width="120px" ref="form" :rules="rules1">
              <el-form-item label="地址：" prop="address">
                <el-input v-model.trim="form.address" autocomplete="off" style="width:200px;"></el-input>
              </el-form-item>
              <el-form-item label="标准名称：" prop="checkName">
                <el-input v-model.trim="form.checkName" autocomplete="off" style="width:200px;"></el-input>
              </el-form-item>
              <el-form-item label="状态：" prop="state" >
                <el-select v-model="form.state"   filterable placeholder="请选择" style="width:auto;" @change="getstate">
                  <el-option label="启用" value="0"></el-option>
                  <el-option label='禁用' value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="检验标准文件：" prop="standard" >
                <el-upload
                    class="upload-daoru"
                    ref="upload"
                    :action="action"
                    :on-change="uploadonchange"
                    accept=".xlsx,.xls"
                    :limit="1"
                    :show-file-list='true'
                    :auto-upload="false"
                    :file-list="fileList"
                >
                  <el-button slot="trigger" type="primary" size="small">点击上传</el-button>
                </el-upload>
              </el-form-item>


            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取 消</el-button>
              <el-button type="primary"   @click="save('form')">确 定</el-button>
            </div>
          </el-dialog>
        </el-form>

    </div>
</template>

<script>
import {check_save,check_findById,check_update,check_add} from '@/request/api'
import uploadImg from '../../../common/uploadImg';
import { mapState } from 'vuex';
    export default {
        components: {
            uploadImg
        },
        data() {
            return {
              form:{
                file:'',
                fileName:'',
          states:''
              },
              fileList:[],
              action:'',
              dialogFormVisible:false,
                standard:'',
				        title:'',
                ifshow:true,
                imgurl:'',
                show:true,
                labelPosition:'right',
                showForm: false,
                ruleForm: {
                    type:'',
                    description:'',
                    basis:[],
                    // files:''
                    standard:1
                },
                tableData: [

                ],
                listUrl:'',
                id:'',
                rules:{
                    standard:[
                        { required: true, message: '不能为空', trigger: 'change' }
                    ],
                    checkName: [
                        { required: true, message: '不能为空', trigger: 'blur' }
                    ],
                    checkName2:[
                      { required: true, message: '不能为空', trigger: 'blur' }
                    ],

                },
              rules1:{
                checkName: [
                  { required: true, message: '不能为空', trigger: 'blur' }
                ],
                address: [
                  { required: true, message: '不能为空', trigger: 'blur' }
                ],
                state: [
                  { required: true, message: '不能为空', trigger: 'change' }
                ],
              },
              addoredit:false,
              index:'',
              arr:""
            };
        },
        computed:{
            ...mapState(['switchHeadTab'])
        },
        mounted(){
          // console.log(this.$route)
          if(this.$route.path == "/checkingBasis/added"){
            this.title = "新增检验检测"
            // console.log(111)
          }
          if(this.$route.path == "/checkingBasis/edit"){
            this.title = "编辑检验检测"
            // console.log(222)
          }
            console.log(this.$route.query)
            this.id= this.$route.query.id
            this.ruleForm.type = this.$route.query.type
            this.ruleForm.standard = this.$route.query.standard
            this.ruleForm.id = this.$route.query.id
            // if(this.id == undefined){
            // console.log(this.$route.query.arr)
            if(this.$route.query.arr != undefined){
                this.arr = JSON.parse(this.$route.query.arr)
            }

            if(this.arr){
                if(this.arr.standard == '国标'){
                    this.arr.standard = '1'
                }else if(this.arr.standard == '省标'){
                    this.arr.standard = '2'
                }else if(this.arr.standard == '省标-北京'){
                    this.arr.standard = '3'
                }else if(this.arr.standard == '省标-上海'){
                    this.arr.standard = '4'
                }
                console.log(this.arr,'$$$$');
                this.ruleForm = this.arr

                // console.log(this.arr)
                if(this.ruleForm.type == "配方颗粒" && this.ruleForm.standard == "2"){

                    if(this.ruleForm.checkName){
                        this.tableData = JSON.parse(this.ruleForm.checkName)
                        if(this.tableData.length){
                            console.log(2)
                            for (let i = 0; i <this.tableData.length ; i++) {
                                if(this.tableData[i].state == 0){
                                    this.tableData[i].states = "启用"
                                }else if(this.tableData[i].state == 1){
                                    this.tableData[i].states= "禁用"
                                }
                            }
                        }else{
                            console.log(111)
                            this.tableData = []
                        }
                    }
                }
                if(this.ruleForm.oldBasis){
                    this.ruleForm.oldBasis = this.ruleForm.basis
                    const arr = this.ruleForm.basis.split(";")
                    if(arr == ""){

                    }else{
                        this.listUrl = arr.map(t =>{
                            var obj = {}
                            obj.url =this.$store.state.imageUrls + t
                            obj.name = this.$store.state.imageUrls + t
                            return obj
                        })
                    }
                }

                // this.ruleForm.breedNameId = this.arr.breedNameId
                // this.ruleForm.breedName = this.arr.breedName
            }
            // }else{
            //     this.init()
            // }
            if(this.$route.query.type == '中药饮片(半成品)'){
                this.ruleForm.type = this.$route.query.type
            }
        },
        methods: {
          handledel(index,row){
            this.tableData.splice(index,1)
          },

          handleEdit(index,row){
            this.addoredit = true
            this.index = index
            this.dialogFormVisible = true
            this.form = this.tableData[index]
            if(this.tableData[index].fileName){
              this.fileList  =[{name:this.tableData[index].fileName}]
            }else{
              this.fileList = []
            }
          },
          getstate(){
            if(this.form.state == 0){
              this.form.states = "启用"
            }else if(this.form.state == 1){
              this.form.states = "禁用"
            }
          },

          save(formName){
            this.$refs[formName].validate((valid)=>{
              if(valid){
                // console.log(this.tableData)
                this.dialogFormVisible = false
                if(this.addoredit == false){
                  this.tableData.push(this.form)
                }else if(this.addoredit == true){
                  this.tableData[this.index] = this.form
                  this.$set(this.tableData[this.index],"fileName",this.form.fileName)
                  this.$set(this.tableData[this.index],"states",this.form.states)
                }
                this.form = {
                  file:""
                }
                this.fileList = []
              }else{
                return false
              }
            })
          },
          uploadonchange(file) {
            this.form.fileName = file.name
            this.form.file = file.raw
            this.$notify({
              title: '提示',
              message: '上传成功',
              type: 'success'
            });
          },
          handleadded(){
            this.addoredit =false
            this.dialogFormVisible = true
            this.form = {
              file:''
            }
            this.fileList = []
          },
            editback(){
                this.show = true
                this.showForm = false
            },
            init(){
                check_findById(this.id).then((res)=>{
                    this.ruleForm = res.data
                  // this.ruleForm.checkNameDTOList = []
                  if(this.ruleForm.type == "配方颗粒" && this.ruleForm.standard == "2"){
                    this.tableData = JSON.parse(this.ruleForm.checkName)
                    for (let i = 0; i <this.tableData.length ; i++) {
                      if(this.tableData[i].state == 0){
                        this.tableData[i].states = "启用"
                      }else if(this.tableData[i].state == 1){
                        this.tableData[i].states= "禁用"
                      }
                    }
                  }

                    this.ruleForm.oldBasis = res.data.basis
                    const arr = this.ruleForm.basis.split(";")
                    if(arr == ""){

                    }else{
                        this.listUrl = arr.map(t =>{
                            var obj = {}
                            obj.url =this.$store.state.imageUrls + t
                            obj.name = this.$store.state.imageUrls + t
                            return obj
                        })
                    }
                })
            },
            deleteUnit(index){
                this.$confirm('是否确定删除该条工艺描述?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.units.splice(index,1)
                        this.$notify({
                            title: '提示',
                            message: '删除成功',
                            type: 'success',
                            duration:1000
                        });
                    }).catch(() => {
                        this.$notify({
                            title: '提示',
                            message: '已取消删除',
                            type: 'info',
                            duration:1000
                        });
                    });
            },
            backPage () {
                this.$router.go(-1);
                this.$store.commit('settype',this.ruleForm.type)
            },
            submitForm() {
              if(this.ruleForm.type == "配方颗粒" && this.ruleForm.standard !=1){
                let formdata = new FormData()
                for(let i=0;i<this.tableData.length;i++){
                  formdata.append("files",this.tableData[i].file)
                }
                this.ruleForm.checkName = JSON.stringify(this.tableData)
                for(var a in this.ruleForm){
                  if(this.ruleForm[a] == null || this.ruleForm[a] == "null"){
                    this.ruleForm[a] = ""
                      formdata.append(a,'')
                  }else{
                    formdata.append(a,this.ruleForm[a])
                  }
                }
                formdata.delete("checkNameDTOList")
                if(this.id == undefined){
                  check_save(formdata).then((res)=>{
                    this.$notify({
                      title: '提示',
                      message: '保存成功',
                      type: 'success',
                      duration:1000
                    });
                    this.$router.go(-1)
                  })
                }else{
                  console.log(formdata)
                  check_update(formdata).then((res)=>{
                    this.$notify({
                      title: '提示',
                      message: '修改成功',
                      type: 'success',
                      duration:1000
                    });
                    this.$router.go(-1)
                  })
                }
              }else{
                var imgurls = this.$refs.uploadChang.fileList
                let formdata = new FormData()
                var arr=""
                for(var i=0;i<imgurls.length;i++){
                  if(imgurls[i].status != "success"){
                    formdata.append("files",imgurls[i].raw)
                  }
                  arr += imgurls[i].name + ';'
                }
                var str = arr.substr(0,arr.length-1)
                this.ruleForm.basis = str.substring(str.lastIndexOf("/")+1)
                for(var a in this.ruleForm){
                  if(this.ruleForm[a] == null || this.ruleForm[a] == "null"){
                    this.ruleForm[a] = ""

                      formdata.append(a,'')
                  }else{
                    formdata.append(a,this.ruleForm[a])
                  }
                }

                formdata.delete("checkNameDTOList")
                if(this.id == undefined){
                  formdata.delete('id')

                  check_save(formdata).then((res)=>{
                    this.$notify({
                      title: '提示',
                      message: '保存成功',
                      type: 'success',
                      duration:1000
                    });
                    this.$router.go(-1)
                  })
                }else{
                  if(this.ruleForm.type == '提取饮片'){
                    check_add(formdata).then((res)=>{
                      this.$notify({
                        title: '提示',
                        message: '修改成功',
                        type: 'success',
                        duration:1000
                      });
                      this.$router.go(-1)
                    })
                  }else{
                    check_update(formdata).then((res)=>{
                      this.$notify({
                        title: '提示',
                        message: '修改成功',
                        type: 'success',
                        duration:1000
                      });
                      this.$router.go(-1)
                    })
                  }

                }
              }



            },
            submitrule(formName){
            console.log(this.ruleForm)
                if(this.ruleForm.standard == 1){
                    this.standard = "国标"
                }else if(this.ruleForm.standard == 2){
                     this.standard = "省标"
                }else if(this.ruleForm.standard == 3){
                     this.standard = "省标-北京"
                }else if(this.ruleForm.standard == 4){
                     this.standard = "省标-上海"
                }

                // if(this.$refs.uploadChang.fileList.length>0){
                //     this.imgurl = this.$refs.uploadChang.fileList[0].url
                // }else{
                //     this.imgurl = ""
                // }
                // if(this.imgurl == ""){
                //     this.ifshow = false
                // }else{
                //     this.ifshow = true
                // }

                this.$refs[formName].validate((valid)=>{
                    if(valid){
                        this.showForm= true
                        this.show = false
                    }else{
                        return false
                    }
                })
            }

        }
    }
</script>
<style scoped lang="less">
/deep/.el-dialog{
  display: flex;
  flex-direction: column;
  margin:0 !important;
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%);
  max-height:calc(100% - 30px);
  max-width:calc(100% - 30px);
  width:25%;
}
// .customWidth{
// 	width:30%;
// }
/deep/.upload-daoru{
  // background: #eee;
  .el-upload{
    border: none;
    width: auto;
    height: auto;
    border-radius: 0;
    // float: right;
    margin-right: 10px
  }
}
.delete_btn{
    margin-left:6px;
}
</style>
